#!/usr/bin/python

'''
######################################
Copyright 2012 Drake Aronhalt (drakearonhalt@gmail.com)
License info here
PyDupes finds duplicate files in a targer directory
#######################################
'''
import os
import sys
import hashlib

###### FUNCTION DEFINITIONS ######

#Hashes a file
#ARG: a file name(str)
#RETURN: hash of file in hex
def hash_file(file_name):
    m = hashlib.md5()
    buf = open(file_name,'rb')
    data = buf.read()
    m.update(data)
    return m.hexdigest()

#Compare hashes to determine duplicates
#ARGS: two hashes in hex
#RETURN: True if hashes match else false
def compare_hash(a, b):
    if hash_file(a) == hash_file(b):
        return True
    else:
        return False

#Parses command line options
#ARGS: options(str) from sys.argv[1]
#RETURN: mode(int)
def parse_options(options):
    if len(options) == 2:
        if options[1] == 'i':
            return 2
        else:
            print usage
            sys.exit()
    else:
        print usage
        sys.exit()

#Interactive mode
#ARGS: 2 file names(str)
#RETURN: NULL
def interactive_delete(a,b):
    print 'files',a,'and',b,'are duplicates'
    print 'Choose a file to delete'
    print '(1)',a
    print '(2)',b
    print ('or neither (press \'n\')')
    answer = raw_input()
    if answer == '1':
        os.remove(a)
    elif answer == '2':
        os.remove(b)

#prints  duplicate files (not useful yet)
#ARGS: 2 file names(str)
#RETURN: NULL
def print_dups(a,b):
    print a,'\t',b

###### END FUNCTION DEFINITIONS ######
###### VARIABLE DEFINITIONS ######

mode = 1
usage = """ Usage: pydupes [OPTIONS] <target_directory>
                   -i             interactive mode"""
###### END VARIABLE DEFINITIONS ######
###### MAIN SCRIPT ######

#check args
if len(sys.argv) == 2 and not (os.path.isdir(sys.argv[1])):
    print sys.argv[1],'is not a directory'
    print usage
    sys.exit()  
elif len(sys.argv) == 2:
    target = sys.argv[1]
elif len(sys.argv[2]):
    target = sys.argv[2]
    mode = parse_options(sys.argv[1])
else: 
    print usage
    sys.exit()    

#change current working to target directory
os.chdir(target)

#get list of files in directory and filesize
files = os.listdir(os.curdir)
file_list = []
dirs = 0

for index,f in enumerate(files):
    if os.path.isdir(f):
        dirs = dirs + 1
        continue
    file_list.append(list([f]))
    statinfo = os.stat(f)
    file_list[index-dirs].append(statinfo.st_size)

#iterate over lists to compare file sizes
#add indices of matching file sizes to list
for index_a,a in enumerate(file_list):
    for index_b, b in enumerate(file_list):
        if index_a >= index_b:
            continue
        elif a[1] == b[1]:
            if compare_hash(a[0],b[0]):
                if mode == 1:
                    print_dups(a[0],b[0])
                else:
                    interactive_delete(a[0],b[0])
